﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Vroom.Services.Common;


namespace Vroom.Services.Client
{
	class Program
	{
		/*
			http://dotnetmentors.com/wcf/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract.aspx 
		 */

		static void Main(string[] args)
		{
			GetOrderDetails("10250");	
		}


		private static void GetOrderDetails(string orderID)
        {

			try
			{
				string requestUrl = string.Format("http://localhost:58619/OrderService.svc/GetOrderDetails/{0}", orderID); 
				HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
				using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
				{
					if (response.StatusCode != HttpStatusCode.OK)
						throw new Exception(String.Format(
						"Server error (HTTP {0}: {1}).",
						response.StatusCode,
						response.StatusDescription));
										
					#region Play with Newtonsoft.Json
					
					//Play with this library wich seems prevalent
					//OrderContract m = JsonConvert.DeserializeObject<OrderContract>(result.Substring(25,result.Length-26));

					#endregion
					
					#region Read Stream into String
					//using (var reader = new StreamReader(responseStream))
					//{
					//	string result = reader.ReadToEnd(); // do something fun...
					//} 
					#endregion

					Stream responseStream = response.GetResponseStream();
					DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(OrderContract));
					object objResponse = jsonSerializer.ReadObject(responseStream);
					OrderContract jsonResponse = objResponse as OrderContract;
					
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				
			}


            WebClient proxy = new WebClient();
			string serviceURL = string.Format("http://localhost:58619/OrderService.svc/GetOrderDetails/{0}", orderID); 
            byte[] data = proxy.DownloadData(serviceURL);
            Stream stream = new MemoryStream(data);
            DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(OrderContract));
            OrderContract order = obj.ReadObject(stream) as OrderContract;

            Console.WriteLine("Order ID : " + order.OrderID);
            Console.WriteLine("Order Date : " + order.OrderDate);
            Console.WriteLine("Order Shipped Date : " + order.ShippedDate);
            Console.WriteLine("Order Ship Country : " + order.ShipCountry);
            Console.WriteLine("Order Total : " + order.OrderTotal);
        }



	}
}
